package com.serverapk.util;

import android.content.Context;
import android.util.Log;


import com.coremedia.iso.boxes.Container;
import com.googlecode.mp4parser.FileDataSourceImpl;
import com.googlecode.mp4parser.authoring.Movie;
import com.googlecode.mp4parser.authoring.builder.DefaultMp4Builder;
import com.googlecode.mp4parser.authoring.tracks.h264.H264TrackImpl;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class H264Saver {
    private BufferedOutputStream outputStream;
    private long frameCount = 0;
    private boolean isAbleWrite = false;
    private String savePath;
    private Context context;

    public H264Saver(String savePath, Context context) {
        this.savePath = savePath;
        this.context = context;
        createfile(savePath);
    }

    private void createfile(String path) {
        //String path = Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator+"test.mp4";
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
        try {
            outputStream = new BufferedOutputStream(new FileOutputStream(file));
            isAbleWrite = true;
        } catch (FileNotFoundException e) {
            ToastUtil.showLong(context, e.toString());
            e.printStackTrace();
        }
    }

    public void writeData(byte[] data, int len, int type) {
        if (outputStream != null) {
            try {
                if (frameCount == 0) {
                    //第一帧必须是主帧
                    if (type == 0xf0) {
                        outputStream.write(data, 0, len);
                        frameCount++;
                    } else {
                        Log.e("DEBUG", "非主帧，丢弃");
                    }
                } else {
                    outputStream.write(data, 0, len);
                    frameCount++;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void close() {
        try {
            outputStream.flush();
            outputStream.close();
            isAbleWrite = false;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void newH264ToMp4(String mp4Path, String h264Path) {
        if (h264Path == null) {
            return;
        }
        File mp4File = new File(mp4Path);
        FileOutputStream fos = null;
        try {
            //这里传入的file是指H264格式对应的文件
            H264TrackImpl h264Track = new H264TrackImpl(new FileDataSourceImpl(h264Path));
            Movie m = new Movie();
            m.addTrack(h264Track);

            Container out = new DefaultMp4Builder().build(m);
            //这里传入的就是要保存的mp4文件目录
            fos = new FileOutputStream(mp4File);
            FileChannel fc = fos.getChannel();
            out.writeContainer(fc);
        } catch (Exception e) {
//            senMsg(e.toString(),11);
//            EventBus.getDefault().post("1:" + e.toString());
            L.e("newH264ToMp4 err:" + e.toString());
//            PrintToFileUtil.input2File("存视频失败1-"+mp4Path+":"+e.toString(),PrintToFileUtil.PATH);
            e.printStackTrace();
        } finally {
            try {
                if (null != fos)
                    fos.close();
            } catch (IOException e) {
                L.e("io err" + e.toString());
//                EventBus.getDefault().post("2:" + e.toString());
//                PrintToFileUtil.input2File("存视频失败2-"+mp4Path+":"+e.toString(),PrintToFileUtil.PATH);
                e.printStackTrace();
            }
        }

    }

}
